package com.share.domain;

import com.share.dbutils.QueryFactory;
import com.share.entity.User;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.SQLException;

/**
 * Created by leep on 2015-12-25.
 */
public class UserDomainImpl implements UserDomain {
	public boolean saveUser(User user) {
		QueryRunner queryRunner = QueryFactory.getQueryRunner();
		return false;
	}

	public User getUserByName(String userName) {
		try {
			QueryRunner queryRunner = QueryFactory.getQueryRunner();
			ResultSetHandler handler = new BeanHandler(User.class);
			String sql = "select * from users where name=?";
			User user = (User) queryRunner.query(sql, handler, userName);
			return user;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

	}

	public String registerUser(User user) {
		User exitUser = getUserByName(user.getName());
		if (exitUser != null) {
			return "用户名已经存在";
		}
		try {
			QueryRunner queryRunner = QueryFactory.getQueryRunner();
			String sql = "insert into users(mobile,name,password) values(?,?,?)";
			ResultSetHandler<User> handler = new BeanHandler<User>(User.class);
			User o = queryRunner.insert(sql, handler, user.getMobile(), user.getName(), user.getPassword());
			user.setId(o.getId());
			return "成功";
		} catch (SQLException e) {
			e.printStackTrace();
			return "异常";
		}
	}
}
